package com.xhs.zdl.demo.citypickerview;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.citylist.CityListSelectActivity;
import com.lljjcoder.citylist.bean.CityInfoBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.citywheel.CityPickerView;
import com.xhs.zdl.demo.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class CitypickerviewDemo extends AppCompatActivity {

    private String addressJson = "{\n" +
            "  \"msg\": \"返回成功\",\n" +
            "  \"code\": \"200\",\n" +
            "  \"results\": {\n" +
            "    \"config\": [\n" +
            "      {\n" +
            "        \"鑫豪斯大楼1\": [\n" +
            "          {\n" +
            "            \"一层\": [\n" +
            "              \"西区\",\n" +
            "              \"东区\",\n" +
            "              \"北区\"\n" +
            "            ]\n" +
            "          },\n" +
            "          {\n" +
            "            \"三层\": [\n" +
            "              \"西区\",\n" +
            "              \"东区\",\n" +
            "              \"北区\"\n" +
            "            ]\n" +
            "          }\n" +
            "        ]\n" +
            "      },\n" +
            "      {\n" +
            "        \"鑫豪斯大楼2\": [\n" +
            "          {\n" +
            "            \"一层\": [\n" +
            "              \"西区\",\n" +
            "              \"东区\",\n" +
            "              \"北区\"\n" +
            "            ]\n" +
            "          },\n" +
            "          {\n" +
            "            \"二层\": [\n" +
            "              \"西区\",\n" +
            "              \"东区\",\n" +
            "              \"北区\"\n" +
            "            ]\n" +
            "          },\n" +
            "          {\n" +
            "            \"三层\": [\n" +
            "              \"西区\",\n" +
            "              \"东区\",\n" +
            "              \"北区\"\n" +
            "            ]\n" +
            "          }\n" +
            "        ]\n" +
            "      }\n" +
            "    ]\n" +
            "  }\n" +
            "}";
    private ArrayList<Map> data;
    private CityPickerView cityPicker;
    private Button ganged_btn1;
    private TextView ganged_value1;
    private Button ganged_btn2;
    private TextView ganged_value2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ganged_demo);

        findView();
        initView();
    }

    private void initView(){
        data = new ArrayList<>();

        //详细属性设置，如果不需要自定义样式的话，可以直接使用默认的，去掉下面的属性设置，直接build()即可。
        CityConfig cityConfig = new CityConfig.Builder(CitypickerviewDemo.this)
//                .title("选择地区")
//                .titleBackgroundColor("#E9E9E9")
//                .textSize(18)
//                .titleTextColor("#585858")
//                .textColor("0xFF585858")
//                .confirTextColor("#0000FF")
//                .cancelTextColor("#000000")
                .province("四川")
                .city("成都")
                .district("龙泉驿区")
//                .visibleItemsCount(5)
//                .provinceCyclic(false)
//                .cityCyclic(false)
//                .districtCyclic(false)
//                .itemPadding(5)
//                .setCityInfoType(CityConfig.CityInfoType.BASE)
//                .setCityWheelType(CityConfig.WheelType.PRO_CITY_DIS)
                .build();

        ganged_btn1.setOnClickListener(onClickListener);
        ganged_btn2.setOnClickListener(onClickListener);
        //配置属性
        cityPicker = new CityPickerView(cityConfig);

        //监听方法，获取选择结果
        cityPicker.setOnCityItemClickListener(new CityPickerView.OnCityItemClickListener() {
            @Override
            public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {

                //ProvinceBean 省份信息
                //CityBean     城市信息
                //DistrictBean 区县信息
//                MyUtils.Log(province.getName()+city.getName()+district.getName());
                String provinceStr = "";
                String cityStr = "";
                String districtStr = "";
                if (null != province)
                    provinceStr = province.getName();
                if (null != city)
                    cityStr = city.getName();
                if (null != district)
                    districtStr = district.getName();
                ganged_value1.setText(provinceStr + cityStr + districtStr);
            }

            @Override
            public void onCancel() {

            }
        });
    }

    private void findView() {
        ganged_btn1 = (Button) findViewById(R.id.ganged_btn1);
        ganged_value1 = (TextView) findViewById(R.id.ganged_value1);
        ganged_btn2 = (Button) findViewById(R.id.ganged_btn2);
        ganged_value2 = (TextView) findViewById(R.id.ganged_value2);
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.ganged_btn1:
                    showPicker1();
                    break;
                case R.id.ganged_btn2:
                    showPicker2();
                    break;
            }
        }
    };

    private void showPicker1() {
        cityPicker.show();
    }

    private void showPicker2() {
        //首先跳转到列表页面，通过startActivityForResult实现页面跳转传值
        Intent intent = new Intent(CitypickerviewDemo.this, CityListSelectActivity.class);
        startActivityForResult(intent, CityListSelectActivity.CITY_SELECT_RESULT_FRAG);
    }

    //接收选择器选中的结果：
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CityListSelectActivity.CITY_SELECT_RESULT_FRAG) {
            if (resultCode == RESULT_OK) {
                if (data == null) {
                    return;
                }
                Bundle bundle = data.getExtras();

                CityInfoBean cityInfoBean = (CityInfoBean) bundle.getParcelable("cityinfo");

                if (null == cityInfoBean)
                    return;

                //城市名称
                String cityName = cityInfoBean.getName();
                //纬度
                String latitude = cityInfoBean.getLongitude();
                //经度
                String longitude = cityInfoBean.getLatitude();

                //获取到城市名称，经纬度值后可自行使用...
                ganged_value2.setText(cityName);
            }
        }
    }

    /**
     * 解析json数据
     * @param object
     * @return
     * @throws JSONException
     */
    private Map<String, Object> getSitesMap(JSONObject object) throws JSONException {
        Map<String, Object> mapData = new HashMap<>();

        Iterator<String> keys = object.keys();
        List<String> keyList = new ArrayList<>();
        while (keys.hasNext()){
            keyList.add(keys.next());
        }
        for (int i = 0; i < keyList.size(); i++) {
            String key = keyList.get(i);
            JSONArray jsonArray = object.getJSONArray(key);
            List<String> tempList1 = new ArrayList<>();
            List<Map<String, Object>> tempList2 = new ArrayList<>();
            for (int j = 0; j < jsonArray.length(); j++) {
                if (!(jsonArray.get(0) instanceof String)) {
                    Map<String, Object> tempMap = getSitesMap(jsonArray.getJSONObject(j));
//                    tempList2.add(tempMap);
                    if (mapData.containsKey(key)) {
                        Map<String, Object> oldMap = (Map<String, Object>) mapData.get(key);
                        oldMap.putAll(tempMap);
                    }else
                        mapData.put(key, tempMap);
                }else {
                    tempList1.add(jsonArray.getString(j));
                    mapData.put(key, tempList1);
                }
            }
        }

        return mapData;
    }

}
